package com.test.prolenders.fragment_prolenders.main_prolenders;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager2.widget.ViewPager2;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;

import com.test.prolenders.analytics_prolenders.util_prolenders.AnalyticsUtil_prolenders;
import com.test.prolenders.R;
import com.test.prolenders.activity_prolenders.ln_prolenders.LnAplyActivity_prolenders;
import com.test.prolenders.activity_prolenders.ln_prolenders.MainActivity_prolenders;
import com.test.prolenders.activity_prolenders.process_prolenders.ProcessActivity_prolenders;
import com.test.prolenders.adapter_prolenders.HomeCarouselAdapter_prolenders;
import com.test.prolenders.base_prolenders.BaseLnFragment_prolenders;
import com.test.prolenders.bean_prolenders.config_prolenders.AppShowCustomize_prolenders;
import com.test.prolenders.bean_prolenders.process_prolenders.ProcessInfo_prolenders;
import com.test.prolenders.bean_prolenders.userinfo_prolenders.LnLimitInfo_prolenders;
import com.test.prolenders.config_prolenders.PermissionConfig_prolenders;
import com.test.prolenders.config_prolenders.UserState_prolenders;
import com.test.prolenders.dialog_prolenders.CustomerServiceDialog_prolenders;
import com.test.prolenders.dialog_prolenders.ProcessBottomDialog_prolenders;
import com.test.prolenders.util_prolenders.UserInfoUtil_prolenders;
import com.test.prolenders.util_prolenders.http_prolenders.HttpUtil_prolenders;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class HomeFragment_prolenders extends BaseLnFragment_prolenders implements EasyPermissions.PermissionCallbacks,EasyPermissions.RationaleCallbacks{

    private final ArrayList<HomeCarouselAdapter_prolenders.HomeCarouseInfo> homeCarouseInfos = new ArrayList<>();

    private ImageButton customerserviceIb;
    private ViewPager2 carouseViewpage2;
    private Button applyBtn;
    private View processView,dsView,contactusView;

    private Runnable processRunnable;

    private final Runnable applyRunnable = () -> {

        HttpUtil_prolenders.getInstance().saveBuriedPoint(page,"APPLY_CLICK","");

        String[] homePermissions = AppShowCustomize_prolenders.getInstance().getHomePermission();

        if (PermissionConfig_prolenders.checkPermissions(requireActivity(), homePermissions)) {
            //device info upload
            try {
                if (UserInfoUtil_prolenders.getInstance().didLogin()) {
                    AnalyticsUtil_prolenders.INSTANCE.saveDeviceS2SInfo();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //申请流程
            processRunnable = () -> {
                //无流程：跳转到申请页
                if (ProcessInfo_prolenders.getInstance().getSteps().isEmpty())
                    startActivity(new Intent(requireActivity(), LnAplyActivity_prolenders.class));
                //有流程：跳转到流程页
                else startActivity(new Intent(requireContext(), ProcessActivity_prolenders.class));
            };

            HttpUtil_prolenders.getInstance().userProcess(requireActivity(),this::onUserProcessResponse);

        } else
            EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_all_prolenders), PermissionConfig_prolenders.PermissionCode_Home, homePermissions);

    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        page = "HOME";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_prolenders, container, false);

        customerserviceIb = view.findViewById(R.id.fh_ib_customerservice);
        carouseViewpage2 = view.findViewById(R.id.fh_viewpage2);
        applyBtn = view.findViewById(R.id.fh_btn_apply);
        processView = view.findViewById(R.id.fh_view_process);
        dsView = view.findViewById(R.id.fh_view_ds);
        contactusView = view.findViewById(R.id.fh_view_contactus);

        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.fh_refreshlayout);
        refreshLayout.setOnRefreshListener(() -> {
            HttpUtil_prolenders.getInstance().saveBuriedPoint(page,"REFRESH_CLICK","");
            refreshLayout.setRefreshing(false);
            HttpUtil_prolenders.getInstance().userProcess(requireActivity(),this::onUserProcessResponse);
        });

        initView();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        HttpUtil_prolenders.getInstance().requestLnLimit(requireActivity(),this::onLnLimitResponse);
    }

    private void initCarouse(){

        homeCarouseInfos.clear();

        homeCarouseInfos.add(new HomeCarouselAdapter_prolenders.HomeCarouseInfo(LnLimitInfo_prolenders.getInstance().getLimitAmount(), false));
        homeCarouseInfos.addAll(LnLimitInfo_prolenders.getInstance().getHomeCarouseInfos());

        HomeCarouselAdapter_prolenders homeCarouselAdapterProlenders = new HomeCarouselAdapter_prolenders(requireContext(),homeCarouseInfos);
        carouseViewpage2.setAdapter(homeCarouselAdapterProlenders);

        new Thread(() -> {
            int count=0;
            while (++count<Integer.MAX_VALUE){
                try {
                    Thread.sleep(1992);
                    int nextIndex = carouseViewpage2.getCurrentItem()+1;
                    if (nextIndex<Integer.MAX_VALUE-2)
                        requireActivity().runOnUiThread(() -> carouseViewpage2.setCurrentItem(nextIndex));
                    Thread.sleep(2814);
                } catch (InterruptedException|IllegalStateException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }).start();

    }

    private void initView(){

        customerserviceIb.setOnClickListener(v -> new CustomerServiceDialog_prolenders(requireContext()).show());
        contactusView.setOnClickListener(v -> new CustomerServiceDialog_prolenders(requireContext()).show());

        //申请
        applyBtn.setOnClickListener(v -> applyRunnable.run());

        processView.setOnClickListener(v -> {
            processRunnable = () -> new ProcessBottomDialog_prolenders(requireContext(),applyRunnable).show();
            HttpUtil_prolenders.getInstance().userProcess(requireActivity(),this::onUserProcessResponse);
        });

        dsView.setOnClickListener(v -> {
            String agreementUrl = AppShowCustomize_prolenders.getInstance().getAgreementUrl();
            if (TextUtils.isEmpty(agreementUrl)) return;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(agreementUrl)));
        });

    }

    public void onUserProcessResponse(){
        String state = ProcessInfo_prolenders.getInstance().getUserState();
        if (UserState_prolenders.isStateChange(state)) {//刷新用户状态
            FragmentActivity activity = requireActivity();
            UserState_prolenders.clearState();
            activity.startActivity(new Intent(activity, MainActivity_prolenders.class));
            activity.finish();
        }else if (processRunnable!=null) {
            processRunnable.run();
            processRunnable = null;
        }else HttpUtil_prolenders.getInstance().requestLnLimit(requireActivity(),this::onLnLimitResponse);
    }

    public void onLnLimitResponse(){
        initCarouse();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        applyRunnable.run();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this,perms))
            new AppSettingsDialog.Builder(this).build().show();
    }

    @Override
    public void onRationaleAccepted(int requestCode) {}

    @Override
    public void onRationaleDenied(int requestCode) {}

}